package com.study.crypto.annotation.validation;

import com.study.crypto.annotation.FixedValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 参数为固定值校验
 * @author Songjin
 * @since 2021-01-10 19:03
 */
public class FixedValueValidator implements ConstraintValidator<FixedValue, Object> {
    
    private List<String>  values;
    private List<Integer> intValues;
    private boolean required;
    
    @Override
    public void initialize(FixedValue fixedValue) {
        this.required = fixedValue.required();
        this.values = Arrays.asList(fixedValue.values());
        this.intValues = new ArrayList<>();
        for (int val : fixedValue.intValues()) {
            this.intValues.add(val);
        }
    }
    
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (!required && value == null) {
            return true;
        }
        if (required && value == null) {
            return false;
        }
        if (value instanceof String) {
            return this.values.contains(value);
        } else if (value instanceof Integer) {
            return this.intValues.contains(value);
        }
        return false;
    }
}
